package java高并发核心编程.多线程.交替打印;

//通过一个volatile类型的变量来控制
public class Demo2 {
    private static volatile int number = 1;
    private static final int MAX = 100;
    private static volatile boolean flag = true;

    public static void main(String[] args) {
        Thread odd = new Thread(new OddThread(), "奇数线程");
        Thread even = new Thread(new EvenThread(), "偶数线程");
        odd.start();
        even.start();
    }

    //奇数线程
    static class OddThread implements Runnable {
        @Override
        public void run() {
            while (number < MAX) {
                while (flag) {
                    System.out.println(Thread.currentThread().getName() + "-->" + number);
                    number++;
                    flag = false;
                }
            }
        }
    }

    //偶数线程
    static class EvenThread implements Runnable {

        @Override
        public void run() {
            while (number <= MAX) {
                while (!flag) {
                    System.out.println(Thread.currentThread().getName() + "-->" + number);
                    number++;
                    flag = true;
                }
            }
        }
    }
}
